package com.goldgov.code.meta.semantics.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import com.goldgov.code.meta.semantics.SemanticsTranslate;

/**
 * 本类不可单例使用，否则项目转义值不会动态刷新
 * @author LHG
 *
 */
public class PorjectSemanticsTranslate implements SemanticsTranslate{

	private Map<String,String> mappingMap = new HashMap<>();
	private Map<String,Map<String,String>> projectMappingMap;
	private final String projectID;
	private final DataSource dataSource;
	
	public PorjectSemanticsTranslate(DataSource dataSource,String projectID) {
		this.dataSource = dataSource;
		this.projectID = projectID;
		try (Connection connection = dataSource.getConnection();
				PreparedStatement prepareStatement = connection.prepareStatement("SELECT ATTRIBUTE_NAME,SEMANTICS_NAME FROM CG_GLOBAL_SEMANTICS");
				ResultSet executeQuery = prepareStatement.executeQuery();
			){
			while(executeQuery.next()) {
				mappingMap.put(executeQuery.getString("ATTRIBUTE_NAME"), executeQuery.getString("SEMANTICS_NAME"));
			}
		} catch (Exception e) {
			throw new RuntimeException("查询转义信息时错误",e);
		}
		
	}
	
	@Override
	public String translate(String translate) {
		String lowerText = translate.toLowerCase();
//		String string = mappingMap.get(lowerText);
		if(projectMappingMap == null){
			projectMappingMap = new HashMap<>();
			try (Connection connection = dataSource.getConnection();
					PreparedStatement prepareStatement = connection.prepareStatement("SELECT ATTRIBUTE_NAME,SEMANTICS_NAME FROM CG_PROJECT_SEMANTICS WHERE PROJECT_ID='" + projectID+"'");
					ResultSet executeQuery = prepareStatement.executeQuery();
				){
				Map<String,String> mappingMap = new HashMap<>();
				while(executeQuery.next()) {
					mappingMap.put(executeQuery.getString("ATTRIBUTE_NAME").toLowerCase(), executeQuery.getString("SEMANTICS_NAME"));
				}
				projectMappingMap.put(projectID, mappingMap);
			} catch (Exception e) {
				throw new RuntimeException("查询转义信息时错误",e);
			}
		}
		
		Map<String, String> kvMap = projectMappingMap.get(projectID);
		if(kvMap.containsKey(lowerText)) {
			return kvMap.get(lowerText);
		}else if(mappingMap.containsKey(lowerText)){
			return mappingMap.get(lowerText);
		}
		
		return translate;
	}

}
